/*
 * @Author: 江舟 jijiangzhou@recycloud.cn
 * @Date: 2024-03-28 16:10:48
 * @LastEditors: 江舟 jijiangzhou@recycloud.cn
 * @LastEditTime: 2024-04-17 17:43:33
 * @FilePath: \vite-project\src\components\common\PageTabs.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import useUserStore from 'store/user';
import { Icon } from '@iconify/react';
import React, { Key, useEffect, useMemo, useRef, useState } from 'react';
import { useLocation, useNavigate, useParams } from 'react-router-dom';

const PageTabs = () => {
    const { menuMap, menuPaths, pageTabs, updatePageTabs } = useUserStore();
    const { pathname } = useLocation();
    const params = useParams();
    const navigate = useNavigate();
    const keys = Object.keys(params || {});
    const [activeRef, setActiveRef] = useState();
    const getRef = (ref, item) => {
        if (ref) {
            if (item.path === pathname || item.path === parentpath) {
                setActiveRef(ref);
            }
        } else {
            setActiveRef(null);
        }
    };
    const parentpath = useMemo(() => {
        if (keys?.length) {
            // 当path中含有参数时，需要高亮父菜单
            const pathnameList = pathname.split('/');
            let start = pathnameList?.length - 1;
            for (let i = 0; i < keys?.length; i++) {
                pathnameList[start] = `:${keys[i]}`;
                start--;
            }
            const currentPath = pathnameList.join('/');
            return menuMap?.[currentPath]?.parentpath;
        }
        return '';
    }, [pathname, params]);

    const onChange = (path: string) => {
        navigate(path);
    };
    const onDel = (path: string, isActive: boolean) => {
        if (pageTabs?.length === 1) {
            return;
        }
        const newPageTabs = pageTabs.filter((item) => item.path !== path);
        const pageIndex = pageTabs.findIndex((item) => item.path === path);
        if (isActive) {
            navigate(newPageTabs?.[pageIndex - 1]?.path);
        }
        updatePageTabs(newPageTabs);
    };
    useEffect(() => {
        if (menuPaths.indexOf(pathname) >= 0) {
            const index = pageTabs.findIndex((item) => item.path === pathname);
            if (index < 0) {
                updatePageTabs([
                    ...pageTabs,
                    {
                        path: pathname,
                        label: menuMap?.[pathname]?.label,
                    },
                ]);
            }
        }
    }, [pathname]);

    useEffect(() => {
        if (activeRef) {
            activeRef?.scrollIntoView?.({ behavior: 'smooth' });
        }
    }, [activeRef]);

    if (pageTabs?.length === 0) {
        return null;
    }

    return (
        <div className='w-full overflow-x-auto overflow-y-hidden bg-white flex'>
            {/* 页签 */}
            <div className='flex items-center p-12px flex-1'>
                {pageTabs?.map((item: any, index: number) => (
                    <div
                        ref={(ref) => getRef(ref, item)}
                        key={index}
                        className={`${
                            item.path === pathname || item.path === parentpath ? 'bg-primary text-white' : 'bg-bgGray'
                        } pl-12px pr-8px leading-24px mr-12px rounded-4px cursor-pointer flex items-center whitespace-nowrap`}
                    >
                        <div onClick={() => onChange(item.path)} className='mr-4px'>
                            {item.label || menuMap?.[menuMap?.[item.path]?.parentPath]?.label}
                        </div>

                        <Icon
                            icon='ant-design:close-outlined'
                            className={`rounded-1/2 transition-all p-2px ${
                                pageTabs?.length === 1
                                    ? 'text-white cursor-not-allowed'
                                    : 'hover:bg-white hover:text-black '
                            }`}
                            onClick={() => onDel(item.path, item.path === pathname || item.path === parentpath)}
                        ></Icon>
                    </div>
                ))}
            </div>
            <div className='w-12px h-24px'></div>
        </div>
    );
};

export default PageTabs;
